package net.oschina.git.hikoyan.helloapi.shiro.jwt.realm;

import net.oschina.git.hikoyan.helloapi.shiro.jwt.authc.UserDefault;
import net.oschina.git.hikoyan.helloapi.shiro.jwt.repository.UserRepository;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * Created by yan on 17/1/17.
 */
public class FormRealm extends AuthorizingRealm {

    private UserRepository userRepository;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token != null && token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo(((UserDefault) principals.getPrimaryPrincipal()).getRoles());
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        UserDefault user = userRepository.findByUsername(upToken.getUsername());
        if (user != null) {
            SimpleAccount account = new SimpleAccount(user, user.getCredentials(), getName());
            return account;
        }
        return null;
    }

    public UserRepository getUserRepository() {
        return userRepository;
    }

    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}
